﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Usido.CRM.IRepository;
using Usido.CRM.Models;
using Usido.CRM.Repository;

namespace Usido.CRM.App.Forms
{
    public partial class 权限控制 : Form
    {
        private readonly ISysMenuRepository SysMenuReposit = new SysMenuRepository();
        private readonly ISysRoleRepository SysRoleReposit = new SysRoleRepository();
        private readonly ISysRoleRightRepository SysRoleRightReposit = new SysRoleRightRepository();
        string[] MenuIds = new string[50];

        public 权限控制()
        {
            InitializeComponent();
            //treeview显示checkbox
            treeView1.CheckBoxes = true;
            this.treeView1.AfterCheck += new TreeViewEventHandler(treeView1_AfterCheck);
        }

        private void 权限控制_Load(object sender, EventArgs e)
        {
            treeView1.ExpandAll();

            InitData();
        }

        private void InitData()
        {
            var List_Role = SysRoleReposit.GetList().ToList();
            SysRole m = new SysRole();
            m.Id = 0;
            m.RoleName = "请选择角色";
            List_Role.Insert(0, m);
            comboBox1.DataSource = List_Role;
            comboBox1.ValueMember = nameof(SysRole.Id);
            comboBox1.DisplayMember = nameof(SysRole.RoleName);

            treeView1.Nodes.Clear();
            DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(int));
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("parent", typeof(int));

            var menulist = SysMenuReposit.GetList().ToList();
            foreach (var menu in menulist)
            {
                dt.Rows.Add(menu.Id, menu.MenuName, menu.ParentId);
            }

            var data = dt.AsEnumerable().Select(dr => new { ID = (int)dr[0], Name = (string)dr[1], Parent = (int)dr[2] });
            foreach (var item in data)
            {

                if (item.Parent == 0)
                {
                    treeView1.Nodes.Add(item.ID.ToString(), item.Name);
                }
                else
                {
                    treeView1.Nodes.Find(item.Parent.ToString(), true)[0].Nodes.Add(item.ID.ToString(), item.Name);
                }
            }
        }


        //取消节点选中状态之后，取消所有父节点的选中状态
        private void setParentNodeCheckedState(TreeNode currNode, bool state)
        {
            TreeNode parentNode = currNode.Parent;

            parentNode.Checked = state;
            if (currNode.Parent.Parent != null)
            {
                setParentNodeCheckedState(currNode.Parent, state);
            }
        }
        //选中节点之后，选中节点的所有子节点
        private void setChildNodeCheckedState(TreeNode currNode, bool state)
        {
            TreeNode parentNode = currNode.Parent;
            if (parentNode != null && parentNode.Text != "")
            {
                currNode.Parent.Checked =true;
            }
            TreeNodeCollection nodes = currNode.Nodes;
            if (nodes.Count > 0)
                foreach (TreeNode tn in nodes)
                {

                    tn.Checked = state;
                    setChildNodeCheckedState(tn, state);
                }
        }
        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Action == TreeViewAction.ByMouse)
            {
                if (e.Node.Checked)
                {
                    //取消节点选中状态之后，取消所有父节点的选中状态
                    setChildNodeCheckedState(e.Node, true);

                }
                else
                {
                    //取消节点选中状态之后，取消所有父节点的选中状态
                    setChildNodeCheckedState(e.Node, false);
                    //如果节点存在父节点，取消父节点的选中状态
                    if (e.Node.Parent != null)
                    {
                        setParentNodeCheckedState(e.Node, false);
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string i = "";
            string roleId = comboBox1.SelectedValue.ToString();
            if (roleId == "0")
            {
                MessageBox.Show("请选择角色");
            }
            else
            {
                foreach (TreeNode tn in treeView1.Nodes)
                {
                    if (tn.Checked)
                        i += tn.Name.Trim() + ",";
                    foreach (TreeNode item in tn.Nodes)
                    {
                        if (item.Checked)
                        {
                            i += item.Name.Trim() + ",";
                        }
                        foreach (TreeNode nd in item.Nodes)
                        {
                            if (nd.Checked)
                            {
                                i += nd.Name.Trim() + ",";
                            }

                        }

                    }
                }
                if (!string.IsNullOrEmpty(i))
                {
                    //清空权限
                    SysRoleRightReposit.DelRole(Convert.ToInt32(roleId));
                    SysRoleRight Role = new SysRoleRight();
                    Role.RoleId = Convert.ToInt32(roleId);
                    string[] MenIds = i.Substring(0, i.Length - 1).Split(',');
                    foreach (var item in MenIds)
                    {
                        Role.MenuId = Convert.ToInt32(item);
                        SysRoleRightReposit.Insert(Role);
                    }
                    MessageBox.Show("权限设置成功");
                }
                else
                {
                    MessageBox.Show("请选择权限！");
                }
            }
            
        }
        //private void DiGui(TreeNode tn)
        //{
        //    foreach (TreeNode tnSub in tn.Nodes)
        //    {
        //        foreach (var item in MenuIds)
        //        {
        //            if (item != null && tnSub.Name == item)
        //            {
        //                tnSub.Checked = true;
        //            }
        //        }
        //        DiGui(tnSub);
        //    }
        //}

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //try
            //{
            //    MenuIds = new string[50];
            //    string roleid = comboBox1.SelectedValue.ToString();
            //    var MenuIdlist = SysRoleRightReposit.GetList(new { RoleId = Convert.ToInt32(roleid) }).ToList();
            //    if (MenuIdlist.Count > 0)
            //    {
            //        for (int i = 0; i < MenuIdlist.Count; i++)
            //        {
            //            MenuIds[i] = MenuIdlist[i].MenuId.ToString();
            //        }
            //        foreach (TreeNode tn in treeView1.Nodes)
            //        {
            //            foreach (var item in MenuIds)
            //            {
            //                if (item != null && tn.Name == item)
            //                {
            //                    tn.Checked = true;
            //                }
            //            }
            //            DiGui(tn);
            //        }
            //    }
            //    else {
            //       //清空权限
            //    }
               
            //}
            //catch (Exception)
            //{
                
            //}
        }
    }
}
